import asyncio
import websockets
import time
import sys, os
import pynput
from mouse import Player, Recorder


class App:

    ws = None

    autoPlayDur = 100
    noDelay = False

    tasks = []
    premiumTasks = []

    @staticmethod
    async def test():
        for i in range(5):
            await App.ws.send('Echo ' + str(5-i))
            print('Echo  ' + str(5-i))
            await asyncio.sleep(1)
        await App.ws.send('Echo测试结束')

    @staticmethod
    async def exec(cmd):
        try:
            await eval(f'eval("App.{cmd}")')
        except AttributeError as e:
            print(e)
            await App.ws.send("方法未实现")
        except Exception as e:
            print(e)
            await App.ws.send("参数错误")

    @staticmethod
    async def setAutoPlayDur(t):
        dur = int(t)
        if dur > 0: 
            App.autoPlayDur = int(t)
            await App.ws.send(f"设置成功，播放间隔{App.autoPlayDur}秒")
        else:
            await App.ws.send("参数错误")

    @staticmethod
    async def autoPlay():
        for i in range(5):
            await App.ws.send('开始播放倒计时... ' + str(5-i))
            await asyncio.sleep(1)
        while True:
            await Player().run()
            for i in range(App.autoPlayDur):
                await asyncio.sleep(1)
                await App.ws.send('再次播放倒计时... ' + str(App.autoPlayDur-i))
            

    @staticmethod
    async def play():
        for i in range(5):
            await App.ws.send('开始播放倒计时... ' + str(5-i))
            await asyncio.sleep(1)

        await App.ws.send('开始播放')

        await Player().run(App.noDelay)

        await App.ws.send('播放结束')

    @staticmethod
    async def record():
        for i in range(5):
            await App.ws.send('倒计时... ' + str(5-i))
            await asyncio.sleep(1)

        await App.ws.send('开始录制(点击屏幕边缘结束)')

        await Recorder().run()

        await App.ws.send('录制结束')

    @staticmethod
    async def kbClose():
        def on_press(key):
            '按下按键时执行。'
            try:
                if key == pynput.keyboard.Key.f9:
                    App.clearSync()
                # elif key == pynput.keyboard.Key.f10:
                #     App.shutdown()
                # else:
                #     print(key)
            except Exception:
                pass
        
        listener = pynput.keyboard.Listener(on_press=on_press)
        listener.setDaemon(True)
        listener.start()

            


    @staticmethod
    async def service(ws, path):
        try:
            # check for secret
            app_secret = await ws.recv()
            if app_secret != 'jnbjt':
                ws.close()
                return

            # listening kb for shutdown
            asyncio.create_task(App.kbClose())

            # start service
            App.ws = ws
            await ws.send('欢迎使用智慧知府')

            while True:
                cmd = await ws.recv()
                App.tasks.append(asyncio.create_task(App.exec(cmd)))

            
                    
                    
        except websockets.exceptions.ConnectionClosedOK as e:
            pass
        # except Exception as e:
        #     print(e)

    @staticmethod
    async def clear():
        for task in App.tasks:
            task.cancel()
        await App.ws.send('任务队列已清空')

    def clearSync():
        for task in App.tasks:
            task.cancel()
        print('任务队列已经清空')

    @staticmethod
    async def setNoDelay():
        App.noDelay = True
        await App.ws.send('延迟已降低')

    @staticmethod
    async def moveToStart():
        await Player().moveToFirst()
        await App.ws.send('已经移动至第一次单击位置')

    @staticmethod
    def shutdown():
        print('shutdown...')
        asyncio.get_running_loop().stop()

if len(sys.argv) < 2:
    print('port required')
    exit(0)

start_server = websockets.serve(App.service, '127.0.0.1', int(sys.argv[1]))

# loop = asyncio.events.new_event_loop()
# asyncio.events.set_event_loop(loop)
# loop.run_until_complete(start_server)
# loop.run_forever()

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

# asyncio.run(start_server)